import os
import suds.metrics as metrics


class Statistics:
    minuteTimer = metrics.Timer()
    duration = 0
    operations = 0
    message = ''
    collectStatisticsInterval = 10
    seconsdInMinute = 60

    statDataDirectoryName = 'c:/temp/statdata/'

    @staticmethod
    def init():
        dir = os.path.dirname(Statistics.statDataDirectoryName)
        if not os.path.exists(dir):
            os.makedirs(dir)

        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception, e:
                print e

    def getStatistics(self):
        Statistics.message = ''
        dir = os.path.dirname(Statistics.statDataDirectoryName)
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            if os.path.isfile(file_path):
                fileDescriptor = file(file_path, "r")
                value = fileDescriptor.readline()
                fileDescriptor.close()
                Statistics.message += '[PID]   ' + str(the_file) + '   operations/min:  ' + str(value) + '<br>'

        return Statistics.message

    def beginMethod(self):
        Statistics.minuteTimer.start()

    def endMethod(self):
        Statistics.operations += 1
        Statistics.minuteTimer.stop()
        Statistics.duration += Statistics.minuteTimer.duration()
        if Statistics.duration > Statistics.collectStatisticsInterval * Statistics.seconsdInMinute:
            Statistics.duration = 0
            filename = Statistics.statDataDirectoryName + str(os.getpid())
            fileDescriptor = file(filename, "w+")
            fileDescriptor.write(str(Statistics.operations / Statistics.collectStatisticsInterval))
            fileDescriptor.close()
            Statistics.operations = 0
            print Statistics.message
